using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace Gko.Utils
{
	public class UnmanagedMemoryStream : Stream
	{
		private readonly bool canRead;
		private readonly bool canWrite;
		private readonly IntPtr ptr;
		private readonly long size;

		public UnmanagedMemoryStream(IntPtr ptr, long size, bool canRead, bool canWrite)
		{
			this.ptr = ptr;
			this.size = size;
			this.canRead = canRead;
			this.canWrite = canWrite;
		}

		///<summary>
		///When overridden in a derived class, gets a value indicating whether the current stream supports reading.
		///</summary>
		///
		///<returns>
		///true if the stream supports reading; otherwise, false.
		///</returns>
		///<filterpriority>1</filterpriority>
		public override bool CanRead
		{
			get
			{
				return this.canRead;
			}
		}

		///<summary>
		///When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
		///</summary>
		///
		///<returns>
		///true if the stream supports seeking; otherwise, false.
		///</returns>
		///<filterpriority>1</filterpriority>
		public override bool CanSeek
		{
			get
			{
				return true;
			}
		}

		///<summary>
		///When overridden in a derived class, gets a value indicating whether the current stream supports writing.
		///</summary>
		///
		///<returns>
		///true if the stream supports writing; otherwise, false.
		///</returns>
		///<filterpriority>1</filterpriority>
		public override bool CanWrite
		{
			get
			{
				return this.canWrite;
			}
		}

		///<summary>
		///When overridden in a derived class, gets the length in bytes of the stream.
		///</summary>
		///
		///<returns>
		///A long value representing the length of the stream in bytes.
		///</returns>
		///
		public override long Length
		{
			get
			{
				return this.size;
			}
		}

		///<summary>
		///When overridden in a derived class, gets or sets the position within the current stream.
		///</summary>
		///
		///<returns>
		///The current position within the stream.
		///</returns>
		///
		public override long Position
		{
			get;
			set;
		}

		/// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception>
		/// <exception cref="IOException">Seek before begin</exception>
		public IntPtr PositionPointer
		{
			get
			{
				return new IntPtr(this.ptr.ToInt64() + this.Position);
			}
			set
			{
				var p = new IntPtr(value.ToInt64() - this.ptr.ToInt64());
				if (p.ToInt64() > 9223372036854775807L) {
					throw new ArgumentOutOfRangeException("value");
				}
				if (p.ToInt64() < 0) {
					throw new IOException("Seek before begin");
				}
				this.Position = value.ToInt64() - this.ptr.ToInt64();
			}
		}

		///<summary>
		///When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
		///</summary>
		public override void Flush()
		{
		}

		///<summary>
		///When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
		///</summary>
		///
		///<returns>
		///The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
		///</returns>
		///
		///<param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset" /> and (<paramref name="offset" /> + <paramref name="count" /> - 1) replaced by the bytes read from the current source. </param>
		///<param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin storing the data read from the current stream. </param>
		///<param name="count">The maximum number of bytes to be read from the current stream. </param>
		///<exception cref="T:System.ArgumentException">The sum of <paramref name="offset" /> and <paramref name="count" /> is larger than the buffer length. </exception>
		///<exception cref="T:System.ArgumentNullException"><paramref name="buffer" /> is null. </exception>
		///<exception cref="T:System.ArgumentOutOfRangeException"><paramref name="offset" /> or <paramref name="count" /> is negative. </exception>
		public override int Read(byte[] buffer, int offset, int count)
		{
			if (buffer == null) {
				throw new ArgumentNullException("buffer");
			}
			if (offset < 0) {
				throw new ArgumentOutOfRangeException("offset", "Need non negative number");
			}
			if (count < 0) {
				throw new ArgumentOutOfRangeException("count", "Need non negative number");
			}
			if ((buffer.Length - offset) < count) {
				throw new ArgumentException("Invalid Offset or Length");
			}
			var readBegin = this.Position;
			var bytesToRead = this.size - readBegin;
			if (bytesToRead > count) {
				bytesToRead = count;
			}
			if (bytesToRead <= 0L) {
				return 0;
			}
			var bytesReaded = (int)bytesToRead;
			if (bytesReaded < 0) {
				bytesReaded = 0;
			}
			Marshal.Copy(this.ptr, buffer, offset, count);
			this.Position = readBegin + bytesToRead;
			return bytesReaded;
		}

		///<summary>
		///When overridden in a derived class, sets the position within the current stream.
		///</summary>
		///
		///<returns>
		///The new position within the current stream.
		///</returns>
		///
		///<param name="offset">A byte offset relative to the <paramref name="origin" /> parameter. </param>
		///<param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position. </param>
		///<exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
		///<exception cref="T:System.ArgumentOutOfRangeException"><c>offset</c> is out of range.</exception>
		/// <exception cref="T:System.ArgumentException">Invalid Seek Origin</exception>
		public override long Seek(long offset, SeekOrigin origin)
		{
			if (offset > 9223372036854775807L) {
				throw new ArgumentOutOfRangeException("offset");
			}
			switch (origin) {
				case SeekOrigin.Begin:
					if (offset < 0L) {
						throw new IOException("Seek Before Begin");
					}
					this.Position = offset;
					break;

				case SeekOrigin.Current:
					if ((offset + this.Position) < 0L) {
						throw new IOException("Seek Before Begin");
					}
					this.Position += offset;
					break;

				case SeekOrigin.End:
					if ((this.size + offset) < 0L) {
						throw new IOException("Seek Before Begin");
					}
					this.Position = this.size + offset;
					break;

				default:
					throw new ArgumentException("Invalid Seek Origin");
			}
			return this.Position;
		}

		///<summary>
		///When overridden in a derived class, sets the length of the current stream.
		///</summary>
		///
		///<param name="value">The desired length of the current stream in bytes. </param>
		public override void SetLength(long value)
		{
			throw new InvalidOperationException();
		}

		///<summary>
		///When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
		///</summary>
		///
		///<param name="buffer">An array of bytes. This method copies <paramref name="count" /> bytes from <paramref name="buffer" /> to the current stream. </param>
		///<param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin copying bytes to the current stream. </param>
		///<param name="count">The number of bytes to be written to the current stream. </param>
		///<exception cref="T:System.ArgumentException">The sum of <paramref name="offset" /> and <paramref name="count" /> is greater than the buffer length. </exception>
		///<exception cref="T:System.ArgumentNullException"><paramref name="buffer" /> is null. </exception>
		///<exception cref="T:System.ArgumentOutOfRangeException"><paramref name="offset" /> or <paramref name="count" /> is negative. </exception>
		///<exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
		///<exception cref="T:System.NotSupportedException">The stream does not support writing. </exception>
		public override void Write(byte[] buffer, int offset, int count)
		{
			if (buffer == null) {
				throw new ArgumentNullException("buffer");
			}
			if (offset < 0) {
				throw new ArgumentOutOfRangeException("offset", "Need non negative number");
			}
			if (count < 0) {
				throw new ArgumentOutOfRangeException("count", "Need non negative number");
			}
			if ((buffer.Length - offset) < count) {
				throw new ArgumentException("Invalid Offset or Length");
			}
			var start = this.Position;
			var length = this.size;
			var end = start + count;
			if (end < 0L) {
				throw new IOException("Stream Too Long");
			}
			if (end > length) {
				if (end > this.size) {
					throw new NotSupportedException("Fixed Capacity");
				}
			}
			Marshal.Copy(buffer, offset, this.PositionPointer, count);
			this.Position = end;
		}
	}
}